package com.tzy.for10evalue.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tzy.for10evalue.designpattern.strategy.ServiceFactory;
import com.tzy.for10evalue.entity.OrderDto1;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author tzy
 * @date 2022/5/27 15:10
 */
@RestController
public class TestController {
    @Autowired
    private ServiceFactory serviceFactory;

//    @PostConstruct
    public void sendTest() {
//        serviceFactory.execute(1L,"123","content");
        serviceFactory.execute(2L, "123", "content");
//        serviceFactory.execute(3L,"123","content");
    }

  /*  @PostConstruct
    public void test() {
        List<OrderDto1> orderList = new ArrayList() {{
            add(new OrderDto1("30000001", "45000001", "add1"));
            add(new OrderDto1("30000001", "45000002", "add1"));
            add(new OrderDto1("30000002", "45000003", "add1"));
            add(new OrderDto1("30000002", "45000004", "add1"));
            add(new OrderDto1("30000003", "45000005", "add1"));
            add(new OrderDto1("30000003", "45000006", "add1"));
        }};
        orderList.stream().collect(Collectors.groupingBy(OrderDto1::getSalecercificate));
    }*/

    //异步导出
 /*   public ResultEntity exportPerformance(DlPerformanceQO dlPerformanceQO, HttpServletResponse response, String repeatExportIn30Min) {
        String systemUserId = LoginUserUtil.getUser().getSystemUserId();
        SystemUserBase systemUser = systemUserService.getUserById(systemUserId);
        DlRoleMenuFunction roleFunctionByRole = menuRoleService.getRoleFunctionByRoles(systemUser.getSystemUserId(), 58);
        String canSelect = roleFunctionByRole.getCanselect();
        Assert.notNull(canSelect, "无导出权限,请联系管理员");
        try {
            //校验当前登陆人半小时内导出
            EntityWrapper<DlExportRecord> dlExportRecordEntityWrapper = new EntityWrapper<>();
            dlExportRecordEntityWrapper.eq("create_user", systemUser.getSystemUserId());
            dlExportRecordEntityWrapper.orderBy("create_time", false);
            dlExportRecordEntityWrapper.eq("type", "4");
            List<DlExportRecord> dlExportRecordHsitoryList = dlExportRecordService.selectList(dlExportRecordEntityWrapper);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(dlExportRecordHsitoryList)) {
                //取最近一条
                Date latestDate = dlExportRecordHsitoryList.get(0).getCreateTime();
                Duration duration = Duration.between(LocalDateTime.ofInstant(latestDate.toInstant(), ZoneId.systemDefault()), LocalDateTime.now());
                Long exportInterval = duration.toMinutes();
                if (exportInterval <= 30) {
                    if (repeatExportIn30Min.equals("0")) {
                        ResultEntity resultEntity = ResultEntity.error("最近导出过类似内容，导出内容将发送至您的邮箱，请耐心等耐，避免重复操作，是否继续导出？");
                        resultEntity.setResultCode("8888");
                        return resultEntity;
                    }
                }
            }

            List<SaleOrderPerformanceBO> saleOrderPerformanceBOList = null;
            //录入导出记录
            SystemUserBase user = LoginUserUtil.getUser();
            DlExportRecord dlExportRecord = new DlExportRecord("4", org.apache.commons.collections.CollectionUtils.isNotEmpty(saleOrderPerformanceBOList) ? saleOrderPerformanceBOList.size() : 0, "1", user.getInternalEMailAddress());
            LoginUserUtil.setCreateLoginMsg(dlExportRecord);
            dlExportRecordService.insert(dlExportRecord);

            final NewExcelUtil newExcelUtil = new NewExcelUtil(response, "业绩表", SaleOrderPerformanceBO.class);
            int page = 1;
            while (true) {
                dlPerformanceQO.setCurrPage(page);
                PageInfo<DlSalePerformanceEntity> salePerformanceEntityList = PageHelper.startPage(dlPerformanceQO.getCurrPage(), 2000).doSelectPageInfo(() -> dlSalePerformanceDao.selectBySaleCertificatesAndWebsitecode(dlPerformanceQO));
                salePerformanceEntityList.getList().forEach(item -> {
                    String belongtowebsite = item.getWebsiteCode();
                    if (StringUtils.isNotEmpty(belongtowebsite)) {
                        Customer customer = customerMapper.selectByCrmCustomerCode(Integer.valueOf(belongtowebsite));
                        item.setBelongTowebsiteCodeStr(customer == null ? "" : customer.getCustomername());
                    }
                });
                List<SaleOrderPerformanceBO> list = BeanUtilCopy.copyListProperties(salePerformanceEntityList.getList(), SaleOrderPerformanceBO::new);
                newExcelUtil.writerData(list);
                if (!salePerformanceEntityList.isHasNextPage()) {
                    break;
                }
                page++;
            }

            List<SaleOrderPerformanceBO> saleOrderPerformanceExcel = saleOrderPerformanceBOList;
            CompletableFuture.runAsync(() -> {
                //发送附件到邮件
                Workbook wb = newExcelUtil.getWriter().writeContext().writeWorkbookHolder().getWorkbook();
                File file = new File("业绩表" + System.currentTimeMillis() + ".xlsx");
                OutputStream os = null;
                try {
                    os = new FileOutputStream(file);
                    wb.write(os);
                    os.close();
                    String myEmail = systemUser.getInternalEMailAddress();
                    Assert.isTrue(StringUtils.isNotEmpty(myEmail), "您还未维护邮箱信息，请联系管理员处理");
                    emailUtil.sendAttachmentMail(myEmail, "业绩导出", "", file.getName(), file);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    file.delete();
                }
            }, exportExecutor).whenComplete((x, y) -> {
                DlExportRecord exportedRecord = dlExportRecordService.selectById(dlExportRecord.getId());
                exportedRecord.setStatus("1");
                exportedRecord.setExportCount(saleOrderPerformanceExcel.size());
                dlExportRecordService.updateById(exportedRecord);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultEntity.ok("业绩导出成功，稍后将发送至邮箱：" + systemUser.getInternalEMailAddress() + "，请留意邮箱邮件，导出进度可在菜单：数据导出记录中查看，请留意信息安全，避免信息泄露。");
    }*/
}
